from machine import Pin,I2C,lightsleep,RTC
import utime

# import sht31
# import fb
# rtc=RTC()


# print(i2c.scan())
# print(i2c.__class__.__name__!= "I2C")
# sht=sht31.SHT31(i2c)

# a=fb.screen(256,128,0,0)
# a.lcdinit()
SHT20_address       =   64
T_measurement       =   bytes([0b11110011])
RH_measurement      =   bytes([0b11110101])
Write_user_register =   bytes([0b11100110])
Read_user_register  =   bytes([0b11100111])
Soft_reset          =   bytes([0b11111110])

AHT10_address       =   56
AHT10_RESET         =   bytes([0b10111010])
AHT10_WRITE_REG     =   bytes([0b11100001])
AHT10_MEASUREMENT   =   bytes([0b10101100])
'''
i2c.start()
print("i2c.write",i2c.write(b"\x80\xfe"))
i2c.stop()
#print("i2c.write",i2c.write(b"\x80\xe6\x83"))

buf=bytearray(8)
#i2c.writeto(64,b"\xe7\xfe")
#i2c.write(b"\x80\xe7")
i2c.start()
i2c.write(b"\x80\xf5")
i2c.stop()
utime.sleep_ms(200)
i2c.start()
i2c.write(b"\x81")
print(i2c.readinto(buf,False))
i2c.stop()
print(buf)
'''

def sht20C():
    i2c.writeto(SHT20_address,bytearray(T_measurement))
    utime.sleep_ms(100)
    buf=i2c.readfrom(SHT20_address,3)
    t0=buf[0]*256+buf[1]
    i2c.writeto(SHT20_address,bytearray(RH_measurement))
    utime.sleep_ms(80)
    buf=i2c.readfrom(SHT20_address,3)
    t=buf[0]*256+buf[1]
    sht20rt=(t0/65536*175.72)-46.85
    sht20rh=(t/65536*125)-6
    return (sht20rt,sht20rh)

if __name__=="__main__":
    i2c = I2C(0,scl=Pin(5), sda=Pin(4), freq=400000)
    i2c.writeto(SHT20_address,bytearray(Soft_reset))
    #i2c.writeto(AHT10_address,AHT10_RESET)

    utime.sleep_ms(30)

    while True:

        i2c.writeto(SHT20_address,bytearray(T_measurement))
        # #i2c.writeto(AHT10_address,AHT10_MEASUREMENT)
        utime.sleep_ms(100)
        # aht10Buf=i2c.readfrom(AHT10_address,6)
        # ahtRHBuf=(aht10Buf[1]<<12)|(aht10Buf[2]<<4)|((aht10Buf[3]&0xf0)>>4)
        # ahtTBuf=((aht10Buf[3]&0x0f)<<16)|(aht10Buf[4]<<8)|aht10Buf[5]
        # ahtT=((200 * ahtTBuf) / 1048576) - 50
        # ahtHR=ahtRHBuf * 100 / 1048576

        buf=i2c.readfrom(SHT20_address,3)
        t0=buf[0]*256+buf[1]
        i2c.writeto(SHT20_address,bytearray(RH_measurement))
        utime.sleep_ms(80)
        buf=i2c.readfrom(SHT20_address,3)
        # utime.sleep_ms(80)
        t=buf[0]*256+buf[1]
        sht20rt=(t0/65536*175.72)-46.85
        sht20rh=(t/65536*125)-6
        # (aht31t,aht31h)=sht.get_temp_humi()
        # print("AHT10:   %7.3fC\t%f%%"%(ahtT,ahtHR))
        print("sht20:   ",(t0/65536*175.72)-46.85,"C\t",(t/65536*125)-6,"% ")
        # print("sht31:   ","%7.3fC %.3f%%"%(aht31t,aht31h))
        # t=rtc.datetime()
        # print( "{0:0>2d}:{1:0>2d}:{2:0>2d}.{3:0>3d}".format(t[4],t[5],t[6],t[7]) )

        # a.print( "{0:0>2d}:{1:0>2d}:{2:0>2d}".format(t[4],t[5],t[6]) )
        # a.print("sht20: %7.3fC  %.3f%%"%(sht20rt,sht20rh))
        # a.print("sht31: %7.3fC  %.3f%%"%(aht31t,aht31h))
        # a.print("AHT10: %7.3fC  %.3f%%"%(ahtT,ahtHR))
        utime.sleep_ms(2000)